package com.gzist.elderlyserviceplatform.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzist.elderlyserviceplatform.entity.dto.ListQueryPageDTO;
import com.gzist.elderlyserviceplatform.entity.po.Announcement;
import com.gzist.elderlyserviceplatform.entity.vo.HomePageAnnouncementVO;
import com.gzist.elderlyserviceplatform.mapper.AnnouncementMapper;
import com.gzist.elderlyserviceplatform.service.AnnouncementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 公告信息表 服务实现类
 */
@Service
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement> implements AnnouncementService {

    @Override
    public Page<Announcement> list(ListQueryPageDTO listQueryPageDTO) {

        LambdaQueryWrapper<Announcement> wrapper = Wrappers.lambdaQuery();
        wrapper.like(Announcement::getTitle, listQueryPageDTO.getKeyWord());
        return this.page(new Page<>(listQueryPageDTO.getPageNum(), listQueryPageDTO.getPageSize()), wrapper);
    }

    @Override
    public void update(Announcement announcement) {
        LambdaUpdateWrapper<Announcement> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Announcement::getId, announcement.getId());
        this.update(announcement, wrapper);

    }

    @Override
    public List<HomePageAnnouncementVO> getHomePageList() {
        try {
            LambdaQueryWrapper<Announcement> wrapper = Wrappers.lambdaQuery();
            wrapper.orderByDesc(Announcement::getUpdateTime).last("limit 3");
            List<Announcement> list = this.list(wrapper);
            if (list == null) {
                return Collections.emptyList();
            }
            return list.stream()
                    .filter(item -> item != null && item.getUpdateTime() != null)
                    .map(item -> {
                        HomePageAnnouncementVO homePageAnnouncementVO = new HomePageAnnouncementVO();
                        homePageAnnouncementVO.setId(item.getId());
                        homePageAnnouncementVO.setTitle(item.getTitle());
                        homePageAnnouncementVO.setDate(DateUtil.format(item.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
                        return homePageAnnouncementVO;
                    })
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("Error occurred while fetching home page announcements", e);
            throw new RuntimeException(e);
        }
    }

}
